package com.myapp.myhome.activity;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.myapp.myhome.R;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.myapp.myhome.adapter.MySerchAdapter;
import com.myapp.myhome.utils.AllUtils;
import com.myapp.myhome.utils.MainUtils;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

public class SearchPerInfoActivity extends BaseActivity {

	private Button title_btn_back;
	private TextView title_text_title;
	private Spinner spinner_name;
	private Spinner spinner_paystate;
	private TextView text_date;
	private ListView mListView;
	private TextView text_money;
	private TextView text_yufu;
	private TextView text_jiesuan;

	MySerchAdapter adapter;
	List<AVObject> list;

	String str_name = "全部";
	String str_paystate = "未结算";
	String str_data;

	String[] array_who;
	String[] array_pay_state;

	MainUtils mainUtils;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_search_perinfo);
		mainUtils = new MainUtils(this);
		init();
		// 一进来就执行搜索
		searchInfo();

	}

	private void init() {
		title_btn_back = (Button) this.findViewById(R.id.titlebar_back);
		title_btn_back.setVisibility(View.VISIBLE);
		title_btn_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		title_text_title = (TextView) this.findViewById(R.id.titlebar_title);
		title_text_title.setText("搜索");
		// ------------------标题栏设置完毕------------------------
		text_yufu = (TextView) this.findViewById(R.id.perinfo_text_yufu_money);
		text_jiesuan = (TextView) this
				.findViewById(R.id.perinfo_text_jiesuan_money);

		// 设置listview
		mListView = (ListView) this.findViewById(R.id.perinfo_listview);
		adapter = new MySerchAdapter(this);
		mListView.setAdapter(adapter);

		// 下面设置下拉列表
		array_who = getResources().getStringArray(R.array.search_who);
		array_pay_state = getResources().getStringArray(
				R.array.search_pay_state);
		spinner_name = (Spinner) this.findViewById(R.id.perinfo_spinner_name);
		spinner_name.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				text_money.setText("");
				str_name = array_who[position];
				searchInfo();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
		spinner_paystate = (Spinner) this
				.findViewById(R.id.perinfo_spinner_paystate);
		spinner_paystate
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						str_paystate = array_pay_state[position];
						text_money.setText("");
						searchInfo();
					}

					@Override
					public void onNothingSelected(AdapterView<?> parent) {
						// TODO Auto-generated method stub

					}
				});
		// ----------------下面是月份的设置-----------------

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
		long time_val = System.currentTimeMillis();
		Date date = new Date(time_val);
		String str = dateFormat.format(date);

		text_date = (TextView) this.findViewById(R.id.perinfo_text_data);
		text_date.setText(str);
		str_data = text_date.getText().toString();
		text_date.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDatePicker();

			}
		});
		text_money = (TextView) this.findViewById(R.id.perinfo_text_allmoney);
	}

	private void searchInfo() {
		AVQuery<AVObject> query = new AVQuery<AVObject>("Expenses");
		query.whereMatches("date", str_data.substring(0, 7));// 这边将本月的传进去
		query.whereEqualTo("paystate", str_paystate.equals("未结算") ? false
				: true);
		query.orderByDescending("eid");
		if (str_name.equals("全部")) {
			// query.setLimit(50);
		} else {
			query.whereMatches("who", str_name);// 这边将名字传进去

		}
		adapter.setName(str_name);
		query.findInBackground(new FindCallback<AVObject>() {
			public void done(List<AVObject> avObjects, AVException e) {

				if (e == null) {
					list = avObjects;
					adapter.setData(list);
					// AllUtils.showToast(SearchPerInfoActivity.this, "查询成功");
					double all_money = getMoney();
					getYuFu(all_money);
				} else {
					Log.d("失败", "查询失败");
					AllUtils.showToast(SearchPerInfoActivity.this, "查询错误");
				}
			}
		});

	}

	// 显示日期选择器
	private void showDatePicker() {
		Calendar cal = Calendar.getInstance();

		final DatePickerDialog mDialog = new DatePickerDialog(this, null,
				cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
				cal.get(Calendar.DAY_OF_MONTH));
		mDialog.setButton(DialogInterface.BUTTON_POSITIVE, "完成",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 通过mDialog.getDatePicker()获得dialog上的DatePicker组件，然后可以获取日期信息
						DatePicker datePicker = mDialog.getDatePicker();
						int year = datePicker.getYear();
						int month = datePicker.getMonth();
						int day = datePicker.getDayOfMonth();
						SimpleDateFormat dateFormat = new SimpleDateFormat(
								"yyyy-MM");
						Date date = new Date(year - 1900, month, day);
						String str = dateFormat.format(date);
						str_data = str;
						text_date.setText(str_data);
						searchInfo();
					}
				});

		mDialog.setCancelable(true);
		mDialog.setCanceledOnTouchOutside(true);
		mDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "取消",
				new DatePickerDialog.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						dialog.dismiss();
					}
				});

		mDialog.show();
	}

	private double getMoney() {
		double allmoney = 0;
		if (list.size() > 0) {
			if (str_name.equals("全部")) {
				for (int i = 0; i < list.size(); i++) {
					AVObject avlist = list.get(i);
					double money = Double
							.parseDouble(avlist.getString("money"));
					allmoney += money;
				}
			} else {
				for (int i = 0; i < list.size(); i++) {
					AVObject avlist = list.get(i);
					double money = Double.parseDouble(avlist
							.getString("avgpay"));
					allmoney += money;
				}
			}
		}
		BigDecimal b = new BigDecimal(allmoney);
		allmoney = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		text_money.setText(allmoney + "");
		return allmoney;
	}

	// 感觉预付这边需要从数据库再查询一次
	private void getYuFu(final Double money_exp) {
		AVQuery<AVObject> query = new AVQuery<AVObject>("Expenses");
		query.whereMatches("date", str_data.substring(0, 7));// 这边将本月的传进去
		query.whereEqualTo("paystate", str_paystate.equals("未结算") ? false
				: true);
		query.orderByDescending("eid");
		if (str_name.equals("全部")) {
			query.whereMatches("whopay", "舍费");
		} else {
			query.whereMatches("whopay", str_name);// 这边将名字传进去
		}
		query.findInBackground(new FindCallback<AVObject>() {

			@Override
			public void done(List<AVObject> arg0, AVException arg1) {
				if (arg1 == null) {
					// 这边对集合进行操作,然后得到数据
					double yufu_money = 0;
					if (arg0.size() > 0) {
						for (int i = 0; i < arg0.size(); i++) {
							AVObject av_list = arg0.get(i);
							double money = Double.parseDouble(av_list
									.getString("money"));
							yufu_money += money;
						}
					}
					
					BigDecimal b = new BigDecimal(yufu_money);
					yufu_money = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
					text_yufu.setText(yufu_money + "");
					
					double money_js = yufu_money - money_exp;// 结算的金额
					BigDecimal decimal = new BigDecimal(money_js);
					money_js = decimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
					
					if (money_js >= 0) {
						SpannableStringBuilder builder = new SpannableStringBuilder(
								"可取出" + money_js);
						ForegroundColorSpan redSpan = new ForegroundColorSpan(
								Color.RED);
						builder.setSpan(redSpan, 3, builder.length(),
								Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
						
						text_jiesuan.setText(builder);
					} else {
						text_jiesuan.setText("需上交" + (-money_js));
					}

				} else {
					AllUtils.showToast(SearchPerInfoActivity.this, "预付金额数据获取失败");
					arg1.printStackTrace();
				}
			}
		});
	}
}
